package demo03;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import static org.objectweb.asm.Opcodes.ASM9;
import static org.objectweb.asm.Opcodes.IADD;

public class RemoveZeroAddVisitor extends ClassVisitor {
    protected RemoveZeroAddVisitor(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv  = super.visitMethod(access, name, descriptor, signature, exceptions);
        if(null != mv  && !"<init>".equals(name) && !"<clinit>".equals(name)){
            mv = new RemoveZeroMethodAdapter(ASM9,mv);
            return mv;
        }
        return mv;
    }

    class RemoveZeroMethodAdapter extends MethodVisitor {
        protected RemoveZeroMethodAdapter(int api, MethodVisitor methodVisitor) {
            super(api, methodVisitor);
        }
        private boolean skipNextIADD = false;
         //每个方法的指令都会进入到这个方法里边
        @Override
        public void visitInsn(int opcode) {
            //ASM 为每个操作都定义了一个int类型的变量 比如 IADD = 96 ICONST_0 =3
            if(skipNextIADD){
                if(opcode == IADD){
                    skipNextIADD = false;
                    return;
                }else {
                   skipNextIADD = false;
                }
            }
            if(Opcodes.ICONST_0 == opcode){
                skipNextIADD = true;
            }else{
                //会把当前指令写入文件
                super.visitInsn(opcode);
            }


        }
    }
}
